import {
  getSmsCode
} from '../../share/index'
import {
  verifyCollection
} from '../utils/config'
const nodemailer = require('u-nodemailer')
const db = uniCloud.database()

export async function setVerifyCode ({
  mobile,
  email,
  code,
  expiresIn,
  type,
  sendParams,
  extraData
}) {
  email = email && email.trim()
  mobile = mobile && mobile.trim()
  if (email) {
    const {
      emailToLowerCase
    } = this._getConfig()
    if (emailToLowerCase) {
      email = email.toLowerCase()
    }
  }
  if (!mobile && !email) {
    return {
      code: 50101,
      messageValues: {
        param: '手机号或邮箱'
      }
    }
  }
  if (mobile && email) {
    return {
      code: 50102,
      messageValues: {
        param: '参数',
        reason: '手机号和邮箱不可同时存在'
      }
    }
  }
  if (!code) {
    code = getSmsCode()
  }
  if (!expiresIn) {
    expiresIn = 180 // 默认180s过期时间
  }
  const now = Date.now()
  const record = {
    mobile,
    email,
    type,
    code,
    state: 0,
    ip: this.context.CLIENTIP,
    created_at: now,
    expired_at: now + expiresIn * 1000,
    ...(extraData || {})
  }

  await verifyCollection.add(record)
  // 如果是邮箱，判断是否需要发送
  if (email && sendParams) {
    try {
      await sendEmail(sendParams, code, email)
    } catch (e) {
      // TODO handle the exception
    }
  }

  return {
    code: 0,
    mobile,
    email
  }
}

async function sendEmail (sendParams, code, email) {
  var emailConfig = {
    host: sendParams.host,
    port: sendParams.port,
    secure: true,
    auth: {
      user: sendParams.user, // 此处填写要发送邮件的QQ邮箱
      pass: sendParams
        .pass // 此处请自行生成并填写 //注意此处并不是QQ密码,而是QQ邮箱中成功开启POP3/SMTP服务,拿到的授权码,重要的事件说三遍,不是QQ密码,是QQ授权码!不是QQ密码,是QQ授权码!不是QQ密码,是QQ授权码!
    }
  }

  const transporter = nodemailer.createTransport({
    host: emailConfig.host,
    port: emailConfig.port,
    secure: emailConfig.secure, // use SSL
    auth: emailConfig.auth
  })

  const logo = sendParams.logo
  const mailOptions = {
    from: emailConfig.auth.user,
    to: email,
    subject: sendParams.subject,
    html: `<table align="center" cellpadding="0" cellspacing="0" class="wrapper" style="min-height: 100%; width: 100%; background: linear-gradient( 235deg, rgba(252, 237, 240) 0, #d2e3f9 50%, #e7f0fc 100% );">
  <tbody>
    <tr>
      <td>
      <table align="center" cellpadding="0" cellspacing="0" class="wrapper" style="margin: 100px auto; max-width: 800px; background-color: #fff;">
        <tbody>
          <tr>
            <td style="padding: 70px 100px;">
            <div style="background-color: #fff; width: 72px; height: 30px; margin-bottom: 65px;"><a href="javascript:void(0)" style="cursor: pointer; display: block; width: 72px; height: 30px;" target="_blank" title="DMDlink 1" rel="noopener"><img border="0" src="${logo}" style="border: 0;border-radius:50%; outline: 0; text-decoration: none; display: block;" width="72"></a></div>

            <table border="0" cellpadding="0" cellspacing="0" class="paragraph">
              <tbody>
                <tr>
                  <td align="left">
                  <div style="width: 600px; font-family: PingFangSC-Medium; font-size: 24px; font-weight: 500; line-height: 32px; letter-spacing: 0; color: #1f2126;">${sendParams.text}</div>
                  </td>
                </tr>
                <tr>
                  <td align="left">
                  <div style="font-family: PingFangSC-Regular; font-size: 16px; font-weight: 400; line-height: 33px; letter-spacing: 0; color: #1f2126; margin-top: 4px;">您正在进行绑定验证，请输入以下验证码：</div>
                  </td>
                </tr>
                <tr>
                  <td align="left">
                  <div style="height: 64px; border-radius: 4px; background: #f7f7f7; box-sizing: border-box; border: 1px solid #e8e8e8; text-align: center; line-height: 64px; margin: 24px 0; font-size: 32px; font-weight: 500; color: #1f2126; letter-spacing: 10px;">${code}</div>
                  </td>
                </tr>
                <tr>
                  <td align="left">
                  <div style="font-size: 16px; font-weight: 400; line-height: 28px; letter-spacing: 0; color: #1f2126;">如非本人操作，请您放心忽略此邮件。</div>
                  </td>
                </tr>
                <tr>
                  <td align="left">
                  <div style="border-bottom: 1px solid #d8d8d8; margin: 24px 0 17px 0;">&nbsp;</div>
                  </td>
                </tr>
              </tbody>
            </table>
            </td>
          </tr>
        </tbody>
      </table>
      </td>
    </tr>
  </tbody>
</table>`
  }
  var res = await transporter.sendMail(mailOptions)
  return res
}

export async function verifyCode ({
  mobile,
  email,
  code,
  type
}) {
  email = email && email.trim()
  mobile = mobile && mobile.trim()
  if (email) {
    const {
      emailToLowerCase
    } = this._getConfig()
    if (emailToLowerCase) {
      email = email.toLowerCase()
    }
  }
  if (!mobile && !email) {
    return {
      code: 50201,
      messageValues: {
        param: '手机号或邮箱'
      }
    }
  }
  if (mobile && email) {
    return {
      code: 50203,
      messageValues: {
        param: '参数',
        reason: '手机号和邮箱不可同时存在'
      }
    }
  }
  if (!code) {
    return {
      code: 50202,
      messageValues: {
        type: this.t(mobile ? 'sms' : 'email')
      }
    }
  }
  const dbCmd = db.command
  const now = Date.now()
  const query = {
    mobile,
    email,
    type,
    code,
    state: 0,
    expired_at: dbCmd.gt(now)
  }
  const record = await verifyCollection.where(query).orderBy('created_at', 'desc').limit(1).get()
  if (record && record.data && record.data.length > 0) {
    // 验证通过
    const matched = record.data[0]
    // 状态改为已验证
    await verifyCollection.doc(matched._id).update({
      state: 1
    })
    return {
      code: 0,
      msg: '验证通过'
    }
  } else {
    return {
      code: 50202,
      messageValues: {
        type: this.t(mobile ? 'sms' : 'email')
      }
    }
  }
}
